package com.yanfan.data.controller;

import com.alibaba.fastjson.JSONObject;
import com.yanfan.common.annotation.Log;
import com.yanfan.common.core.controller.BaseController;
import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.core.page.TableDataInfo;
import com.yanfan.common.enums.BusinessType;
import com.yanfan.common.utils.StringUtils;
import com.yanfan.common.utils.poi.ExcelUtil;
import com.yanfan.data.domain.AddDataSimCardVo;
import com.yanfan.data.domain.DataSimCard;
import com.yanfan.data.domain.DataSimCardRequestParam;
import com.yanfan.data.service.DataSimCardRequestParamService;
import com.yanfan.data.service.DataSimCardService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 流量卡Controller
 *
 * @author kerwincui
 * @date 2024-07-11
 */
@RestController
@RequestMapping("/snCard/dataSimCard")
public class DataSimCardController extends BaseController {
    @Autowired
    private DataSimCardService dataSimCardService;

    @Autowired
    private DataSimCardRequestParamService dataSimCardRequestParamService;

    public static String calcSign(Map<String, String> params, String secret) {
        params = new TreeMap<>(params);
        StringBuilder stringBuilder = new StringBuilder();
        int size = params.size();
        int index = 0;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            index++;
            stringBuilder.append(entry.getKey()).append("=").append(entry.getValue());
            if (index < size) {
                stringBuilder.append("&");
            }
        }
        stringBuilder.append(secret);
        return DigestUtils.sha256Hex(stringBuilder.toString());
    }

    public static String post(String uri, Map<String, String> params) throws Exception {
        HttpPost httpPost = new HttpPost(uri);
        RequestConfig requestConfig = RequestConfig.DEFAULT;
        httpPost.setConfig(requestConfig);
        List<NameValuePair> paramList = new ArrayList<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        UrlEncodedFormEntity paramEntity = new UrlEncodedFormEntity(paramList, "utf-8");
        httpPost.setEntity(paramEntity);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = httpclient.execute(httpPost);
        HttpEntity resultEntity = response.getEntity();
        String result = EntityUtils.toString(resultEntity);
        EntityUtils.consume(resultEntity);
        response.close();
        httpclient.close();
        return result;
    }

    /**
     * 查询流量卡列表
     */
//    //@PreAuthorize("@ss.hasPermi('snCard:dataSimCard:list')")
    @GetMapping("/list")
    public TableDataInfo list(DataSimCard dataSimCard) {
        startPage();
        List<DataSimCard> list = dataSimCardService.selectDataSimCardList(dataSimCard);
        return getDataTable(list);
    }

    /**
     * 获取流量卡详细信息
     */
//    //@PreAuthorize("@ss.hasPermi('snCard:dataSimCard:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(dataSimCardService.selectDataSimCardById(id));
    }

    /**
     * 获取流量卡详细信息
     */
//    //@PreAuthorize("@ss.hasPermi('snCard:dataSimCard:query')")
    @GetMapping(value = "/getInfoCard/{id}")
    public AjaxResult getInfoCard(@PathVariable("id") Long id) {
        DataSimCard dataSimCard = dataSimCardService.selectDataSimCardById(id);

        DataSimCardRequestParam dataSimCardRequestParam = dataSimCardRequestParamService.selectDataSimCardRequestParamById(dataSimCard.getDscRequestParamId());
        AddDataSimCardVo addDataSimCardVo = new AddDataSimCardVo();
        BeanUtils.copyProperties(dataSimCardRequestParam, addDataSimCardVo);
        //发送请求  获取最新的数据
        AjaxResult ajaxResult = this.getDataSimCardInfo(addDataSimCardVo);
        DataSimCard dataSimCardInfo = (DataSimCard) ajaxResult.get("data");

        dataSimCardInfo.setId(dataSimCard.getId());
        dataSimCardService.updateDataSimCard(dataSimCardInfo);
        return success(dataSimCardInfo);
    }

    /**
     * 停卡、启动卡
     *
     * @param id
     * @param status
     * @return
     */
//    //@PreAuthorize("@ss.hasAnyPermi('snCard:dataSimCard:stop')")
    @GetMapping(value = "/stopCard/{id}/{status}")
    public AjaxResult stopCard(@PathVariable("id") Long id, @PathVariable("status") String status) {

        DataSimCard dataSimCard = dataSimCardService.selectDataSimCardById(id);
        DataSimCardRequestParam dataSimCardRequestParam = dataSimCardRequestParamService.selectDataSimCardRequestParamById(dataSimCard.getDscRequestParamId());
        AddDataSimCardVo addDataSimCardVo = new AddDataSimCardVo();
        BeanUtils.copyProperties(dataSimCardRequestParam, addDataSimCardVo);

        JSONObject jsonObject = this.stopOrOpenCard(addDataSimCardVo, status);
        if (!jsonObject.getBoolean("success")) {
            return error(jsonObject.getString("message") + jsonObject.getString("detail"));
        }
        // 开：ACTIVATED_NAME，关：DEACTIVATED_NAME
        if ("ACTIVATED_NAME".equals(status)) {
            if ("activation".equals(dataSimCard.getStatus())) {
                return warn("已激活");
            }
            dataSimCard.setStatus("activation");
        } else if ("DEACTIVATED_NAME".equals(status)) {
            if ("deactivation".equals(dataSimCard.getStatus())) {
                return warn("已停卡");
            }
            dataSimCard.setStatus("deactivation");
        }

        dataSimCardService.updateDataSimCard(dataSimCard);
        return new AjaxResult();
    }

    /**
     * 新增流量卡
     */
//    //@PreAuthorize("@ss.hasPermi('snCard:dataSimCard:add')")
    @Log(title = "流量卡", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AddDataSimCardVo addDataSimCardVo) {
        // 调用第三方接口获取返回结果
        AjaxResult ajaxResult = getDataSimCardInfo(addDataSimCardVo);
        DataSimCard dataSimCardInfo = (DataSimCard) ajaxResult.get("data");
        //请求成功
        if (null != dataSimCardInfo.getIccId()) {
            DataSimCardRequestParam dataSimCardRequestParam = new DataSimCardRequestParam();
            BeanUtils.copyProperties(addDataSimCardVo, dataSimCardRequestParam);

            return dataSimCardService.insertDataSimCard(dataSimCardInfo, dataSimCardRequestParam);
        }
        return error("请确定你输入的参数是否正确：" + ajaxResult.get("msg"));

    }

    /**
     * 流量卡分配列表
     */
//    //@PreAuthorize("@ss.hasPermi('snCard:dataSimCardFp:list')")
    @GetMapping("/dataSimCardFpList")
    public TableDataInfo selectDataSimCardFpList(DataSimCard dataSimCard) {
        startPage();
        List<DataSimCard> list = dataSimCardService.selectDataSimCardFpList(dataSimCard);
        return getDataTable(list);
    }

    /**
     * 分配流量卡
     *
     * @param deptId 机构id
     * @return com.yanfan.common.core.domain.AjaxResult
     * @param: deviceIds 流量卡id字符串
     */
//    //@PreAuthorize("@ss.hasPermi('snCard:dataSimCard:distribution')")
    @ApiOperation("分配设备")
    @PostMapping("/distribution")
    public AjaxResult distribution(@RequestParam("deptId") Long deptId, @RequestParam("dataSimCardIds") String dataSimCardIds) {
        if (null == deptId) {
            return error("请选择分配机构");
        }
        if (StringUtils.isEmpty(dataSimCardIds)) {
            return error("请选择设备");
        }
        return dataSimCardService.distribution(deptId, dataSimCardIds);
    }

    /**
     * 删除流量卡
     */
//    //@PreAuthorize("@ss.hasPermi('snCard:dataSimCard:remove')")
    @Log(title = "流量卡", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(dataSimCardService.deleteDataSimCardByIds(ids));
    }

    /**
     * 导出流量卡列表
     */
//    //@PreAuthorize("@ss.hasPermi('snCard:dataSimCard:export')")
    @Log(title = "流量卡", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DataSimCard dataSimCard) {
        List<DataSimCard> list = dataSimCardService.selectDataSimCardList(dataSimCard);
        ExcelUtil<DataSimCard> util = new ExcelUtil<DataSimCard>(DataSimCard.class);
        util.exportExcel(response, list, "流量卡数据");
    }

    /**
     * 停卡、启动卡
     */
    public JSONObject stopOrOpenCard(AddDataSimCardVo addDataSimCardVo, String status) {
        //app secret
        String secret = addDataSimCardVo.getAppSecret();

        //api url
        String apiUrl = "https://api.simboss.com/2.0/device/modifyDeviceStatus";

        //参数
        Map<String, String> params = new TreeMap<>();

        //系统参数

        params.put("appid", addDataSimCardVo.getAppId());

        params.put("timestamp", String.valueOf(System.currentTimeMillis()));

        //应用参数

        params.put("iccid", addDataSimCardVo.getIccId());

        params.put("status", status);

        //签名
        String sign = calcSign(params, secret);

        params.put("sign", sign);

        //提交请求
        String json = null;
        try {
            json = post(apiUrl.trim(), params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //解析json返回结果， 此处略过
        System.out.println(json);

        return JSONObject.parseObject(json);
    }

    /**
     * 调用第三方接口 获取流量卡信息
     *
     * @param addDataSimCardVo
     * @return
     */
    public AjaxResult getDataSimCardInfo(AddDataSimCardVo addDataSimCardVo) {
        //app secret bc5abed491d63f565f262238e1e20bc2
        String secret = addDataSimCardVo.getAppSecret();

        //api url
        String apiUrl = "https://api.simboss.com/2.0/device/detail";

        //参数
        Map<String, String> params = new TreeMap<>();

        //系统参数
        // appid 102420198130
        params.put("appid", addDataSimCardVo.getAppId());

        params.put("timestamp", String.valueOf(System.currentTimeMillis()));


        //应用参数 898608162623D0547063
        params.put("iccid", addDataSimCardVo.getIccId());

        //签名
        String sign = calcSign(params, secret);

        params.put("sign", sign);

        //提交请求
        String json = null;
        try {
            json = post(apiUrl.trim(), params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //解析json返回结果， 此处略过
        System.out.println(json);

        JSONObject jsonObject = JSONObject.parseObject(json);

        Integer code = jsonObject.getInteger("code");
        String message = jsonObject.getString("message");
        String detail = jsonObject.getString("detail");
        DataSimCard dataSimCard = new DataSimCard();

        if ("0".equals(code.toString())) {
            Object data = jsonObject.get("data");
            JSONObject obj = JSONObject.parseObject(data.toString());


            /**
             *
             *          "ratePlanExpirationDate": "2024-07-31 23:59:59",
             *         "activeDuration": 90,
             *         "ratePlanId": 2444,
             *         "imsi": "460088625407063",
             *         "type": "POOL",
             *         "totalDataVolume": 30,
             *         "orgId": 72564,                  表里没有
             *         "deviceStatus": "ACTIVATED_NAME",
             *         "iccid": "898608162623D0547063",
             *         "useCountAsVolume": false,
             *         "expireDate": "2025-05-31 23:59:59",  表里没有
             *         "cardPoolId": 36050,
             *         "ratePlanEffetiveDate": "2024-07-01 00:00:00",
             *         "msisdn": "1441662547063",
             *         "gprsStatus": "ACTIVATED_NAME",  表里没有
             *         "dataUsage": 0.03125,
             *         "nbCard": false,
             *         "imeiStatus": "NOT_SET",         表里没有
             *         "orgName": "成都市万易零起科技有限公司",  表里没有
             *         "testingExpireDate": "2024-06-18 16:33:16",
             *         "usedDataVolume": 0.03125,
             *         "lastSyncDate": "2024-07-04 11:56:39",       表里没有
             *         "realnameRequired": false,
             *         "speedLimit": 153600,
             *         "realNameCertifystatus": "not-submit",
             *         "retainNumberMonth": 0,              表里没有
             *         "carrier": "cmcc",
             *         "openDate": "2024-06-18 16:33:16",
             *         "retainNumber": false,               表里没有
             *         "iratePlanName": "30M/月",
             *         "startDate": "2024-06-24 00:33:54",
             *         "status": "activation"
             *
             *
             */
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


            dataSimCard.setIccId(obj.getString("iccid"));
            dataSimCard.setStatus(obj.getString("status"));
            dataSimCard.setMsisdn(obj.getString("msisdn"));
            dataSimCard.setIratePlanName(obj.getString("iratePlanName"));
            dataSimCard.setDataUsage((BigDecimal) obj.get("dataUsage"));
            dataSimCard.setTotalDataVolume((BigDecimal) obj.get("totalDataVolume"));
            dataSimCard.setUsedDataVolume((BigDecimal) obj.get("usedDataVolume"));
            Date ratePlanExpirationDate = null;
            Date ratePlanEffetiveDate = null;
            Date testingExpireDate = null;
            Date openDate = null;
            try {
                ratePlanExpirationDate = dateFormat.parse(obj.getString("ratePlanExpirationDate"));
                ratePlanEffetiveDate = dateFormat.parse(obj.getString("ratePlanEffetiveDate"));
                testingExpireDate = dateFormat.parse(obj.getString("testingExpireDate"));
                openDate = dateFormat.parse(obj.getString("openDate"));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            dataSimCard.setRatePlanExpirationDate(ratePlanExpirationDate);

            dataSimCard.setActiveDuration(obj.getString("activeDuration"));
            dataSimCard.setImsi(obj.getString("imsi"));
            dataSimCard.setType(obj.getString("type"));
            dataSimCard.setDeviceStatus(obj.getString("deviceStatus"));
            dataSimCard.setUseCountAsVolume(obj.getString("useCountAsVolume"));
            dataSimCard.setCardPoolid(obj.getString("cardPoolId"));
            dataSimCard.setRatePlanEffetiveDate(ratePlanEffetiveDate);
            dataSimCard.setNbCard(obj.getString("nbCard"));
            dataSimCard.setTestingExpireDate(testingExpireDate);
            dataSimCard.setRealNameCertifyStatus(obj.getString("realNameCertifystatus"));
            dataSimCard.setCarrier(obj.getString("carrier"));
            dataSimCard.setOpenDate(openDate);

        }

        //BeanUtils.copyProperties(data, dataSimCard);
        return new AjaxResult(code, detail, dataSimCard);
    }

}

